<script setup lang="ts">
import { ref, reactive } from 'vue'
import GIF from 'gif.js'
import html2canvas from 'html2canvas'

// 模拟代码流动内容
const codeLines = [
  '// Initializing tree generator...',
  'import { TreeGenerator } from "@/core";',
  'const generator = new TreeGenerator();',
  '',
  '// Setting up parameters...',
  'generator.setHeight(200);',
  'generator.setColor("#2d5a27");',
  'generator.addDecorations(true);',
  'generator.addLights(true);',
  '',
  '// Starting generation process...',
  'await generator.initialize();',
  'await generator.render();',
  'await generator.optimize();',
  '',
  '// Finalizing...',
  'Generating: tree1.gif',
  'Generation completed! ✨'
]

// 树的样式列表
const treeStyles = [
  {
    id: 1,
    name: '经典绿树',
    thumbnail: '/static/tree1.jpeg',
    style: {
      height: 200,
      color: '#2d5a27',
      decorations: true,
      lights: true,
      animation: 'none'
    }
  }
]

// 当前选中的样式
const currentStyle = ref(treeStyles[0].style)

// 控制代码显示
const visibleCode = ref<string[]>([])
const isGenerating = ref(false)

// GIF 生成状态
const gifBlob = ref<Blob | null>(null)
const isRecording = ref(false)

// 选择样式并开始动画
async function selectStyle(style: typeof treeStyles[0]) {
  if (isGenerating.value) return
  
  currentStyle.value = { ...style.style }
  isGenerating.value = true
  isRecording.value = true
  visibleCode.value = []
  gifBlob.value = null

  try {
    // 1. 初始化 GIF 生成器
    const gif = new GIF({
      workers: 2,
      quality: 10,
      width: 800,
      height: 400,
      workerScript: '/node_modules/gif.js/dist/gif.worker.js'
    })

    // 2. 开始录制过程
    const previewContainer = document.querySelector('.preview-container')
    if (!previewContainer) return

    // 3. 逐行显示代码并录制帧
    for (const line of codeLines) {
      visibleCode.value.push(line)
      await new Promise(resolve => setTimeout(resolve, 300))
      
      const canvas = await html2canvas(previewContainer, {
        backgroundColor: '#f5f5f5',
        scale: 1
      })
      gif.addFrame(canvas, { delay: 300 })
    }

    // 4. 添加一些树的动画帧
    for (let i = 0; i < 5; i++) {
      await new Promise(resolve => setTimeout(resolve, 200))
      const canvas = await html2canvas(previewContainer)
      gif.addFrame(canvas, { delay: 200 })
    }

    // 5. 生成最终的 GIF
    gif.on('finished', (blob: Blob) => {
      gifBlob.value = blob
      isRecording.value = false
      
      // 可以选择自动下载
      if (import.meta.env.VITE_UNI_PLATFORM === 'h5') {
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `${style.name}.gif`
        a.click()
      }
    })

    gif.render()
  } catch (error) {
    console.error('GIF generation failed:', error)
    uni.showToast({
      title: '生成失败',
      icon: 'none'
    })
  } finally {
    setTimeout(() => {
      isGenerating.value = false
    }, 2000)
  }
}
</script>

<template>
  <view class="page-container">
    <!-- 左侧样式选择栏 -->
    <scroll-view class="style-sidebar" scroll-y>
      <view 
        v-for="style in treeStyles" 
        :key="style.id"
        class="style-item"
        :class="{ active: currentStyle === style.style }"
        @tap="selectStyle(style)"
      >
        <image 
          :src="style.thumbnail" 
          mode="aspectFill"
          class="style-thumbnail"
        />
        <text class="style-name">{{ style.name }}</text>
      </view>
    </scroll-view>

    <!-- 右侧预览区域 -->
    <view class="preview-container">
      <!-- 左侧树动画 -->
      <view class="tree-preview">
        <view class="recording-indicator" v-if="isRecording">
          <view class="dot"></view>
          Recording...
        </view>
        
        <view 
          class="christmas-tree" 
          :class="{ generating: isGenerating }"
          :style="{
            '--height': `${currentStyle.height}px`,
            '--tree-color': currentStyle.color
          }"
        >
          <view class="tree-body">
            <view class="tree-star">★</view>
            <view v-if="currentStyle.decorations" class="decorations">
              <view v-for="i in 12" :key="i" class="decoration" :style="{
                '--delay': `${i * 0.2}s`
              }">●</view>
            </view>
            <view v-if="currentStyle.lights" class="lights">
              <view v-for="i in 15" :key="i" class="light" :style="{
                '--delay': `${i * 0.1}s`
              }"></view>
            </view>
          </view>
          <view class="tree-trunk"></view>
        </view>
      </view>

      <!-- 右侧代码流动 -->
      <view class="code-preview">
        <view class="code-container">
          <view 
            v-for="(line, index) in visibleCode" 
            :key="index"
            class="code-line"
            :class="{ 'comment': line.startsWith('//') }"
          >
            {{ line }}
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.page-container {
  display: flex;
  min-height: 100vh;
  background-color: #f5f5f5;
  
  // 左侧样式选择栏
  .style-sidebar {
    width: 120px;
    background: #ffffff;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
    
    .style-item {
      padding: 15px;
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      
      &.active {
        background: #f0f0f0;
        
        .style-thumbnail {
          transform: scale(1.05);
          box-shadow: 0 2px 8px rgba(0, 122, 255, 0.2);
        }
        
        .style-name {
          color: #007aff;
        }
      }
      
      .style-thumbnail {
        width: 80px;
        height: 80px;
        border-radius: 10px;
        transition: all 0.3s ease;
      }
      
      .style-name {
        font-size: 12px;
        color: #333;
      }
    }
  }
  
  // 右侧预览容器
  .preview-container {
    flex: 1;
    display: flex;
    padding: 20px;
    gap: 20px;
    
    // 左侧树预览
    .tree-preview {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #ffffff;
      border-radius: 12px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
      
      .christmas-tree {
        position: relative;
        
        &.generating {
          animation: treeGenerate 2s ease-in-out;
        }
        
        .tree-body {
          position: relative;
          width: 0;
          height: 0;
          border-left: calc(var(--height) * 0.3) solid transparent;
          border-right: calc(var(--height) * 0.3) solid transparent;
          border-bottom: var(--height) solid var(--tree-color);
          
          .tree-star {
            position: absolute;
            top: -20px;
            left: 50%;
            transform: translateX(-50%);
            color: #ffd700;
            font-size: 24px;
          }
          
          .decorations .decoration {
            position: absolute;
            color: #ff4081;
            animation: twinkle 1.5s infinite;
            animation-delay: var(--delay);
          }
          
          .lights .light {
            position: absolute;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #ffeb3b;
            animation: blink 1s infinite;
            animation-delay: var(--delay);
          }
        }
        
        .tree-trunk {
          width: 20px;
          height: 40px;
          background: #8b4513;
          margin: 0 auto;
        }
      }
    }
    
    // 右侧代码预览
    .code-preview {
      flex: 1;
      background: #1e1e1e;
      border-radius: 12px;
      padding: 20px;
      overflow: hidden;
      font-family: 'Consolas', monospace;
      
      .code-container {
        height: 100%;
        overflow-y: auto;
        
        .code-line {
          color: #d4d4d4;
          font-size: 14px;
          line-height: 1.5;
          margin-bottom: 8px;
          animation: slideIn 0.3s ease forwards;
          
          &.comment {
            color: #6a9955;
          }
        }
      }
    }
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes treeGenerate {
  0% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}

@keyframes twinkle {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.3; }
}

// 响应式布局
@media screen and (max-width: 768px) {
  .page-container {
    flex-direction: column;
    
    .style-sidebar {
      width: 100%;
      height: 120px;
      white-space: nowrap;
      
      .style-item {
        display: inline-flex;
        padding: 10px;
      }
    }
    
    .preview-container {
      flex-direction: column;
      
      .tree-preview,
      .code-preview {
        height: 40vh;
      }
    }
  }
}

.tree-preview {
  position: relative;
  
  .recording-indicator {
    position: absolute;
    top: 20px;
    left: 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #ff4081;
    font-size: 14px;
    
    .dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #ff4081;
      animation: blink 1s infinite;
    }
  }
}
</style>
